package com.md.notes.model.module.file;

import android.app.Activity;
import android.os.Environment;
import android.widget.Toast;

import com.md.notes.model.entity.Note;
import com.md.notes.model.module.log.LoggerABC;
import com.md.notes.model.module.log.LoggerBuilder;
import com.md.notes.util.FileUtils;
import com.md.notes.util.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FileMgrModel {
    private Activity activity;
    private File mdNotesDir;

    public FileMgrModel() {
        // 获取外部存储根目录
        File rootDir = Environment.getExternalStorageDirectory();
        // 创建 MdNotes 文件夹
        File mdNotesDir = new File(rootDir, "MdNotes");
        if (!mdNotesDir.exists()) {
            if (!mdNotesDir.mkdirs()) {
                Toast.makeText(activity, "创建目录失败", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        this.mdNotesDir = mdNotesDir;
    }

    public void setActivity(Activity activity) {
        this.activity = activity;
    }

    public File getMdNotesDir() {
        return mdNotesDir;
    }

    public List<Note> getNoteList(){
        List<Note> notes = new ArrayList<>();
        File[] fileArray = mdNotesDir.listFiles((File dir,String name)->name.toLowerCase().endsWith(".md"));
        for (int i = 0; i < fileArray.length; i++) {
            File file = fileArray[i];
            try {
                String content = FileUtils.readFileWithUTF8(file.getPath());
                String head = StringUtils.extractBetweenDashes(content);
                Note note = Note.parseFromString(head);
                note.setContent(content);
                notes.add(note);
            }catch (Exception e){
                LoggerABC loggerABC = LoggerBuilder.build(activity);
                loggerABC.setException(e);
                loggerABC.logMessage(LoggerABC.ERROR,"FileMgrModel模块错误");
            }
        }

        return notes;
    }
}
